package com.pf.service.impl;

import com.pf.dto.response.CommodityRespDTO;
import com.pf.dto.response.SalesDTO;
import com.pf.mapper.entity.Sales;
import com.pf.service.CommodityService;
import com.pf.service.ElasticSearchService;
import com.pf.utils.ElasticSearchUtils;
import com.pf.utils.JacksonUtils;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author PanFei
 * @version 1.0.0
 * @createTime 2021/7/27
 */
@Service
@Slf4j
public class ElasticSearchServiceImpl implements ElasticSearchService {

    @Autowired
    private CommodityService commodityService;

    @Override
    public void initIndex(String indexName) {
        try {
            // 如果不存在索引，则创建并初始化数据
            if (!ElasticSearchUtils.isExistingIndex(indexName)) {
                // 准备关于索引的settings
                Settings.Builder settings = Settings.builder()
                        .put("number_of_shards", 3)
                        .put("number_of_replicas", 1);

                // 准备关于索引的结构mappings
                XContentBuilder mappings = JsonXContent.contentBuilder()
                        .startObject()
                        .startObject("properties")
                        .startObject("commodityId")
                        .field("type", "integer")
                        .field("index", false)
                        .endObject()
                        .startObject("commodityName")
                        .field("type", "text")
                        .field("index", true)
                        .endObject()
                        .startObject("commodityPrice")
                        .field("type", "float")
                        .field("index", true)
                        .endObject()
                        .startObject("commodityStock")
                        .field("type", "integer")
                        .field("index", true)
                        .endObject()
                        .startObject("categoryId")
                        .field("type", "integer")
                        .field("index", false)
                        .endObject()
                        .startObject("categoryCode")
                        .field("type", "keyword")
                        .field("index", true)
                        .endObject()
                        .startObject("categoryName")
                        .field("type", "text")
                        .field("index", true)
                        .endObject()
                        .startObject("sales")
                        .field("type", "integer")
                        .field("index", true)
                        .endObject()
                        .endObject()
                        .endObject();

                boolean isAcknowledged = ElasticSearchUtils.createIndex(settings, mappings, indexName);
                log.info("ElasticSearchServiceImpl initIndex 创建索引isAcknowledged：{}", isAcknowledged);
            }

        } catch (IOException e) {
            log.error(">>>>> ElasticSearchServiceImpl initIndex error", e);
        }

    }

    @Override
    public void initData(String indexName) {
        // 查询所有商品信息
        List<CommodityRespDTO> allCommodityList = commodityService.getAllCommodityList();
        Map<Integer, CommodityRespDTO> commodityMaps = allCommodityList.stream().collect(Collectors.toMap(CommodityRespDTO::getCommodityId, item -> item));
        Map<String, String> targetMaps = new HashMap<>();
        if (commodityMaps != null) {
            commodityMaps.forEach((commodityId, obj) -> {
                targetMaps.put(commodityId + "", JacksonUtils.toJsonString(obj));
            });
        }

        if (targetMaps != null) {
            ElasticSearchUtils.batchAddData(indexName, targetMaps);
        }

    }

    @Override
    public void updateSales(String indexName) {
        // 查询商品的销量信息
        List<Sales> sales = commodityService.getAllCommoditySales();
        Map<Integer, Integer> dataMap = sales.stream().collect(Collectors.toMap(Sales::getCommodityId, Sales::getSales));
        Map<String, String> targetMap = new HashMap<>();
        if (dataMap != null) {
            dataMap.forEach((key, value) -> {
                targetMap.put(key + "", JacksonUtils.toJsonString(SalesDTO.builder().sales(value).build()));
            });
        }
        ElasticSearchUtils.batchUpdateData(indexName, targetMap);
    }
}
